// pages/punchCard/punchCard.js
import Time from "../../utils/time"
let Player = require("../../utils/player"),
    audioList = [],
    player = new Player(),
    playerCurrent = {},
    videoContext = {}
const app = getApp();
const api = require('../../utils/interface.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 头部信息 图片 名字 参加人数 打卡人数
    cardInfo: {
      imgUrl: 'http://www.haopic.me/wp-content/uploads/2016/10/20161013124719335.jpg',
      name: '五月绿舍离身体整理健身打卡',
      addNumber: '663',
      punchNumber: '3622',
    },
    userInfo: wx.getStorageSync("userInfo"),
    // 当返回的 评论为0 请返回“”

    //    效果控制
    control: {
      audio: {
        player: {},
        id: "",
        isPlayer: true,
        isPause: false,
        startDate: '00:00',
        progress: "",
        activeProgress: {},
        aniProgress: {},
        loadSucc: false
      },
        movieList:[],
      movie: {}
    },
    show: true, // ture 显示打卡 false 显示成员
    userList: [],
    pkid: 0,
    groupInfo: {},
    detailList: [],
    page: 1,
    size: 10,
    user_page: 1,
    isload_d: false,
    isload_u: false,
    poster: '../../images/timg.jpg',
    name: '',
    author: '',
    userInfo: wx.getStorageSync('userInfo')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
      console.log(app.globalData.userInfo);
      var that = this;
      that.setData({
          userInfo: app.globalData.userInfo
      });
    var that = this;
    that.setData({
      pkid: options.id
    });
    //加载圈子详情
    // that.get_group_info();
    // //加载圈子包含日记
    // that.get_detail_list();

  },
  //获取圈子详情
  get_group_info: function() {
    var that = this;
    app.Post(api.wxapp.clock_group_info, {
      groupId: that.data.pkid,
      hasPerson: false
    }, function(res) {
      if (res.code == 1) {
        that.setData({
          groupInfo: res.data
        });
      }
    });
  },
  //请求圈子日记列表
  get_detail_list: function() {
    var that = this;
    app.Post(api.wxapp.clock_detail_list, {
      groupId: that.data.pkid,
      page: that.data.page,
      size: that.data.size
    }, function(res) {
      if (res.code == 1) {
        that.setData({
          detailList: that.data.detailList.concat(res.data.ClockDetailList)
        });
        that.AudioProgress();
        that.initAudio();
        if (res.data.ClockDetailList.length < that.data.size) {
          that.setData({
            isload_d: true
          });
        } else {
          that.setData({
            page: that.data.page + 1
          });
        }
      }
    });
  },
  //获取成员
  get_person_list: function() {
    var that = this;
    app.Post(api.wxapp.get_person_list, {
      groupId: that.data.pkid,
      page: that.data.user_page,
      size: that.data.size
    }, function(res) {
      if (res.code == 1) {
        that.setData({
          userList: res.data.PersonList
        });
        if (res.data.PersonList.length < that.data.size) {
          that.setData({
            isload_u: true
          });
        } else {
          that.setData({
            user_page: that.data.user_page + 1
          });
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  // 点击红心 发送事件
  bindpraise: function(e) {

    let that = this,
      log = that.data.detailList,
      bind = e.currentTarget.dataset.bind,
      isHeart = log[bind].IsThumbUp,
      userINfo = that.data.userInfo;
    console.log(app.globalData.userInfo);
    var param = {
      detailId: e.currentTarget.dataset.id,
      type: isHeart ? 2 : 1
    };
    app.Post(api.wxapp.clock_detail_thumb, param, function(res) {
      if (res.code == 1) {
        if (!isHeart) {
          log[bind].ThumbsUpList.push({
            AccountId: app.globalData.userInfo.Id,
            Nickname: app.globalData.userInfo.Nickname
          });
          console.log(e.currentTarget.dataset.bind)
          log[bind].IsThumbUp = true
          log[bind].ThumbsUpCount = log[bind].ThumbsUpCount + 1;
        } else {
          var thums = [];
          log[bind].IsThumbUp = false
          log[bind].ThumbsUpCount = log[bind].ThumbsUpCount - 1;
          for (var i = 0; i < log[bind].ThumbsUpList.length; i++) {
            if (log[bind].ThumbsUpList[i].AccountId != app.globalData.userInfo.Id) {
              thums.push(log[bind].ThumbsUpList[i]);
            }
          }
          log[bind].ThumbsUpList = thums;
        }
        that.setData({
          detailList: log
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.isShuaXing==false)
    {
      this.setData({
        isShuaXing:true
      })
      return false;
    }
    this.setData({
      userList: [],
      groupInfo: {},
      detailList: [],
      page: 1,
      size: 10,
      user_page: 1,
      isload_d: false,
      isload_u: false,
    });
    //加载圈子详情
    this.get_group_info();
    //加载圈子包含日记
    this.get_detail_list();
  },
  //切换
  bindSwitch: function(e) {
    var that = this;
    console.log(e)
    let bind = e.currentTarget.dataset.bind,
      show = this.data.show;
    if (bind == 1) {
      show = true;
      that.setData({
        page: 1,
        detailList: []
      });
      that.get_detail_list();
    } else {
      show = false;
      that.setData({
        user_page: 1,
        userList: []
      });
      that.get_person_list();
    }
    this.setData({
      show: show
    })
  },
  skip: function(e) {
    console.log(e.currentTarget.dataset.bind)
    let bind = e.currentTarget.dataset.bind
    if (bind == 2) {
      wx.navigateTo({
        url: '../Billboard/Billboard?id=' + e.currentTarget.dataset.id,
      })
    } else {
      wx.navigateTo({
        url: '../calendar/calendar?id=' + e.currentTarget.dataset.id + '&IsTodayClock=' + this.data.groupInfo.IsTodayClock,
      })
    }
  },
  //点击关注
  touchguanZhu: function(e) {
    var that = this,
      bind = e.currentTarget.dataset.bind,
      isthumbe = e.currentTarget.dataset.isthumbe,
      accountid = e.currentTarget.dataset.accountid;
    //添加关注
    if (!e.currentTarget.dataset.isthumbe) {
      app.Post(api.wxapp.follow_add, {
        accountId: accountid
      }, function(res) {
        if (res.code == 1) {
          app.ShowMsg("关注成功");
        } else {
          app.WxAlert(res.msg);
        }
      });
    } else {
      //取消关注
      app.Post(api.wxapp.follow_delete, {
        accountId: accountid
      }, function(res) {
        if (res.code == 1) {
          app.ShowMsg("取消成功");
        } else {
          app.WxAlert(res.msg);
        }
      });
    }
    //赋值
    if (!isthumbe) {
      that.data.detailList[bind].IsFollowd = true
    } else {
      that.data.detailList[bind].IsFollowd = false
    }
    this.setData({
      detailList: that.data.detailList
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
      return {
          title: '测试分享',
          path: '/page/index/index'
      }
  },
    // 初始化录音
    initAudio: function () {
        const that = this,
            detailList = that.data.detailList;
        player.list.clear()
        let audioData = []
        console.log(detailList)
        console.log(player.list)
        audioList = []
        for (let i = 0; i < detailList.length; i++) {
            if (detailList[i].ContentRadio != "") {
                audioList.push({
                    id: "aa",
                    dataUrl: detailList[i].ContentRadio,
                    title: i,
                    index: i,
                })
            }
        }
        console.log(audioList)
        player.list.create(audioList)
        console.log(player.list.info())

    },
    //    录音播放实例
    createAudioPlay: function (e) {
        const that = this,
            control = that.data.control,
            time = new Time(),
            isPlayer = control.audio.isPlayer,
            url = e.currentTarget.dataset.bind
        let index;
        for (let j = 0; j < audioList.length; j++) {
            if (audioList[j].index == url) {
                console.log(audioList[j])
                index = audioList[j]._id
            }
        }
        console.log(":-------------------")
        console.log(player.list.info())
        control.audio.id = url
        console.log(index)
        player.list.syncIndex(audioList[index])
        console.log(player.list.current())

        console.log("别的")
        console.log(player.list.current())
        //      判断是否点击当前录音
        if (player.list.current() != null && playerCurrent.index != url) {
            player.stop()
            //    初始化进度条    点击别的录音
            that.audioProgressAnimation(0, control.audio.progress, "00:00")
            // 全部停止

            console.log("开始播放别的-----------")
            setTimeout(function () {
                player.invoke(index)
            }, 100)
            control.audio.isPlayer = false
            that.setData({
                control: control
            })

            player.event.on('timeupdate', function (data) {
                console.log("开始监听")
                if (data.status == 1) {
                    console.log(data)
                    let startDate = time.secondConvertMinute(data.currentPosition)
                    console.log(startDate)
                    let actWidth = parseFloat(data.currentPosition / data.duration)
                    console.log(actWidth)
                    that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                    if ((data.duration - data.currentPosition) == 0) {
                        console.log("audio end")
                        player.stop()
                        control.audio.isPlayer = true
                        that.setData({
                            control: control
                        })
                        that.audioProgressAnimation(0, control.audio.progress, "00:00")
                    } else {
                        //that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                    }
                }
            })
        }
        else {
            console.log("点击自己")
            player.event.on('timeupdate', function (data) {
                console.log("开始监听")
                if (data.status == 1) {
                    console.log(data)
                    let startDate = time.secondConvertMinute(data.currentPosition)
                    console.log(startDate)
                    let actWidth = parseFloat(data.currentPosition / data.duration)
                    console.log(actWidth)
                    that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                    if ((data.duration - data.currentPosition) == 0) {
                        console.log("audio end")
                        player.stop()
                        control.audio.isPlayer = true
                        that.setData({
                            control: control
                        })
                        that.audioProgressAnimation(0, control.audio.progress, "00:00")
                    } else {
                        //that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                    }
                }
            })

            //点击当当前的录音
            console.log("ahhh")
            // 是否播放
            if (isPlayer) {
                console.log("创建播放")
                if (player.isPaused()) {
                    console.log("继续播放")
                    player.resume()
                }
                else {
                    if (!player.isPlaying()) {
                        console.log("开始播放")
                        player.invoke(index)
                    }
                }
                console.log(player.list.current())
                control.audio.isPlayer = !isPlayer
                that.setData({
                    control: control
                })

            } else {
                if (!player.isPaused()) {
                    player.pause()
                }
                control.audio.isPlayer = !isPlayer
                that.setData({
                    control: control
                })

            }
        }
        playerCurrent = player.list.current()
        console.log(player.list.current())
    },
    //    录音播放进度条
    AudioProgress: function () {
        const that = this,
            control = that.data.control;
        let systemInfo = {}
        wx.getSystemInfo({
            success: res => {
                systemInfo = res
            }
        })
        control.audio.progress = systemInfo.screenWidth * 0.3
        this.setData({
            control: control
        })
    },
    //    录音播放进度条动画
    audioProgressAnimation: function (activeProgress, progresWidth, startDate) {
        const that = this,
            control = that.data.control,
            activePro = wx.createAnimation({}),
            aniPro = wx.createAnimation({}),
            initact = wx.createAnimation({}),
            initani =  wx.createAnimation({})
        //  根据歌曲播放百分比 获取active长度
        const width = progresWidth * activeProgress
        let actWidth = parseFloat(progresWidth - width)
        activePro.width(width * 2).step()
        aniPro.width(actWidth).step()
        initact.width(0).step()
        initani.width(progresWidth).step()

        control.audio.activeProgress = activePro.export()
        control.audio.aniProgress = aniPro.export()
        control.audio.startDate = startDate
        control.audio.initActProgress = initact.export()
        control.audio.initAniProgress = initani.export()
        that.setData({
            control: control
        });
    },
  discuss: function(e) {
    wx.navigateTo({
      url: '../discuss/discuss?id=' + e.currentTarget.dataset.id + "&accid=" + e.currentTarget.dataset.accid
    });
  },

  // // 点击红心 发送事件
  // isheart: function(e) {
  //   let that = this,
  //     log = that.data.log,
  //     bind = e.currentTarget.dataset.bind,
  //     isHeart = log[bind].interaction.isHeart,
  //     userINfo = that.data.userInfo;
  //   if (!isHeart) {
  //     console.log(e.currentTarget.dataset.bind)
  //     log[bind].interaction.isHeart = true
  //     log[bind].interaction.heartNumber.push(userINfo.nickName)
  //   } else {
  //     log[bind].interaction.isHeart = false
  //     log[bind].interaction.heartNumber.splice(log[bind].interaction.heartNumber.indexOf(userINfo.nickName), 1)
  //   }

  //   that.setData({
  //     log: log
  //   });
  // },
  bindakarili: function(e) {
    console.log(e);
    return
  },
  // 跳转到我的个人页面
  grzy: function(e) {
    wx.navigateTo({
      url: '../grzy/grzy?id=' + e.currentTarget.dataset.accid
    })
  },
  bindMy: function() {
    wx.switchTab({
      url: '../wod/wod',
    })
  },
  bindBack: function() {
    wx.switchTab({
      url: '../index/index',
    })
  },
  binddaka: function() {
    var that = this;
    if (that.data.groupInfo.IsTodayClock) {
      app.WxAlert("一个圈子一天只能打一次卡");
      return;
    }
    if (!that.data.groupInfo.IsJoin) {
      app.WxAlert("您还没有加入" + that.data.groupInfo.GroupName + "圈子");
      return;
    }
    wx.navigateTo({
      url: '../clockIn/clockIn?id=' + that.data.groupInfo.Id
    });
  }
  ,
    imgYu: function (event) {
        var src = event.currentTarget.dataset.src; //获取data-src
        var imgList = event.currentTarget.dataset.list; //获取data-list
        //图片预览
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls: imgList // 需要预览的图片http链接列表
        })
        this.setData({
            isShuaXing: false
        })

    },
    audioPlay: function () {
        this.setData({
            action: {
                method: 'play'
            }
        });
    },
    videlplay:function(e)
    {
        let index = e.currentTarget.dataset.index
        var log = this.data.detailList;
        log[index].isMviePlayer=true;
        videoContext = wx.createVideoContext('myVideo' + index)
        videoContext.index = index
        videoContext.requestFullScreen({
            duration:0
        })
        console.log("full")
        this.setData({
            detailList:log
        })
    },
    fullVideo:function (e) {
        let log = this.data.detailList
        console.log(e)
        console.log(e.detail.fullScreen)
        if(!e.detail.fullScreen){
            videoContext.pause()
            log[videoContext.index].isMviePlayer=false;
            console.log("结束全屏  ")
            this.setData({
                detailList:log
            })
        }
    },
    // 跳转到我的个人页面
    grzy: function (e) {
      wx.navigateTo({
        url: '../grzy/grzy?id=' + e.currentTarget.dataset.accid
      })
      // wx.navigateTo({
      //   url: '../fenxiang/fenxiang?id=' + e.currentTarget.dataset.accid
      // })
    },
})